<h2>Why is this an issue?</h2>
<p>In TypeScript, casts and non-null assertions are two mechanisms used to inform the TypeScript compiler about the intended types of variables,
expressions, or values in the code. They are used to help the compiler understand the types more accurately and to handle certain situations where
type inference might not be sufficient:</p>
<ul>
  <li> A type assertion tells the compiler to treat the value as the specified type, even if the compiler’s type inference suggests a different type.
  </li>
  <li> A non-null assertion is a way to tell the TypeScript compiler explicitly that you are certain that a variable will not be <code>null</code> or
  <code>undefined</code>, and you want to access its properties or methods without any null checks. </li>
</ul>
<p>However, a redundant cast occurs when you perform a type assertion that is not needed because the compiler already knows the type based on the
context or explicit type declarations. Similarly, a redundant non-null assertion occurs when you use the non-null assertion operator <code>!</code> to
assert that a variable is not <code>null</code> or <code>undefined</code>, but the compiler already knows that based on the context.</p>
<p>Both redundant casts and redundant non-null assertions should be avoided in TypeScript code, as they add unnecessary noise, clutter the code, and
lead to confusion.</p>
<pre data-diff-id="1" data-diff-type="noncompliant">
function getName(x?: string | Person) {
  if (x) {
    console.log("Getting name for " + x!); // Noncompliant: 'x' is known to be defined here

    if (typeof x === "string") {
      return (x as string); // Noncompliant: 'x' is known to be a string here
    } else {
      return (x as Person).name; // Noncompliant: 'x' is defined and not a string, thus a 'Person' here
    }
  }
  return "NoName";
}
</pre>
<p>Remove all the redundant casts and non-null assertions based on the contextual typing information, as inferred by the TypeScript compiler.</p>
<pre data-diff-id="1" data-diff-type="compliant">
function getName(x?: string | Person) {
  if (x) {
    console.log("Getting name for " + x);

    if (typeof x === "string") {
      return x;
    } else {
      return x.name;
    }
  }
  return "NoName";
}
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
  <li> <a href="https://typescript-eslint.io/">typescript-eslint</a> - Rule <a
  href="https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unnecessary-type-assertion.mdx">no-unnecessary-type-assertion</a> </li>
  <li> TypeScript Documentation - <a href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions">Type Assertions</a>
  </li>
  <li> TypeScript Documentation - <a
  href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#non-null-assertion-operator-postfix-">Non-null Assertion Operator (Postfix
  <code>!</code>)</a> </li>
</ul>
